package com.udf.service.impl;

import com.udf.bean.ReqResultBean;
import com.udf.service.IURLConnectionService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;


/**
 * Created by 张未然 on 2015/9/2.
 */
@Service
public class URLConnectionService implements IURLConnectionService {


    /**
     * 以GET方法发请求
     * @param url     请求的URL
     * @param param   请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 如果返回的是500 则返回结果。其他的返回responseCode 如404
     */
    @Override
    public ReqResultBean doGet(String url, String param) {
        ReqResultBean result = new ReqResultBean();
        if(!StringUtils.isEmpty(param)){
            url+="?"+param;
        }
        BufferedReader in = null;
        try {
            HttpURLConnection connection = createConnection(url);
            // 建立实际的连接
            connection.connect();
            //如果返回的是302 说明链接跳转了，递归取实际内容数据。
            if(200==connection.getResponseCode()){
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(),"UTF-8"));
                StringBuffer resultBuffer = new StringBuffer();
                String line = "";
                while ((line = in.readLine()) != null) {
                    resultBuffer.append(line);
                }
                result.setContent(resultBuffer.toString());
                result.setCode(connection.getResponseCode());
                result.setSuccess(true);
            }else  if(302==connection.getResponseCode()){
                String redirectUrl = connection.getHeaderField("Location");
                return doGet(redirectUrl,param);
            }else{
                result.setCode(connection.getResponseCode());
                result.setContent(connection.getResponseMessage());
                result.setSuccess(false);
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setSuccess(false);
            if(e instanceof UnknownHostException){
                result.setContent("DNS解析出现异常!请检查网络或者URL拼写是否正确");
            }else{
                result.setContent("发送GET请求出现异常!");

            }
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 以POST方法发请求
     *
     * @param url    发送请求的 URL
     * @param param  请求参数，如：name1=value1&name2=value2。
     * @return 所代表远程资源的响应结果
     */
    @Override
    public ReqResultBean doPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        ReqResultBean result = new ReqResultBean();
        try {
            HttpURLConnection connection = createConnection(url);
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(connection.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();

            //如果返回的是302 说明链接跳转了，递归取实际内容数据。
            if(200==connection.getResponseCode()){
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                StringBuffer resultBuffer = new StringBuffer();
                String line = "";
                while ((line = in.readLine()) != null) {
                    resultBuffer.append(line);
                }
                result.setContent(resultBuffer.toString());
                result.setCode(connection.getResponseCode());
                result.setSuccess(true);
            }else  if(302==connection.getResponseCode()){
                String redirectUrl = connection.getHeaderField("Location");
                return doGet(redirectUrl,param);
            }else{
                result.setCode(connection.getResponseCode());
                result.setContent(connection.getResponseMessage());
                result.setSuccess(false);
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setSuccess(false);
            result.setContent("发送POST请求出现异常！" + e.getMessage());
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return null;
    }

    private HttpURLConnection createConnection(String url) throws IOException {
        HttpURLConnection conn;
        if(!url.contains("://")){
            url = "http://"+url;
        }
        // 打开和URL之间的连接.
        conn = (HttpURLConnection) new URL(url).openConnection();
        // 设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("conn", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        conn.setRequestProperty("Content-type", "text/html");
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setRequestProperty("contentType", "UTF-8");
        conn.setRequestProperty("Charset", "utf-8");
        conn.setInstanceFollowRedirects(true);
        conn.setConnectTimeout(5 * 1000);
        return conn;
    }
}
